package com.eastedu.superise.handler.question.handler.completion;

import com.eastedu.common.model.question.Fragment;
import com.eastedu.common.model.question.QuestionItemContent;
import com.eastedu.superise.handler.question.handler.ContentParser;
import com.eastedu.superise.handler.question.handler.PatternConstant;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

/**
 * The type Stem content parser.
 *
 * @author Administrator
 */
@Slf4j
public class StemContentParser implements ContentParser<ContentSummary> {

    private final Set<Long> questions = Sets.newConcurrentHashSet();

    @Override
    public ContentSummary parse(Long questionId, List<QuestionItemContent> contents) {
        // 第一步提取序号
        String contentString = contents.stream()
                .map(QuestionItemContent::getFragments)
                .flatMap(Collection::stream)
                .map(Fragment::getContent)
                .collect(Collectors.joining());


        Map<Optional<String>, List<String>> details = new HashMap<>(10);
        Matcher matcher = PatternConstant.ORDER_AND_SPACE_PATTERN.matcher(contentString);
        String order = null;
        while (matcher.find()) {
            String order0 = matcher.group("order");
            String space = matcher.group("space");
            if (StringUtils.isNotBlank(order0)) {
                order = order0;
                details.putIfAbsent(Optional.of(order), new ArrayList<>());
            }
            if (StringUtils.isNotBlank(space)) {
                details.computeIfAbsent(Optional.ofNullable(order), s -> new ArrayList<>()).add(space);
            }
        }
        return new ContentSummary(details);
    }

    @Override
    public void print() {
        log.info("括号异常的试题: {}", questions);
    }
}
